import store from '@/store'

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $auth: (module: string, func?: string | string[]) => boolean
  }
}

/**
 * 权限控制指令
 * $auth('模块',['功能'])
 * @param module String
 * @param func String | String[]
 */
export const vAuth = (module: string, func?: string | string[]) => {
  const funcGroup = store.getters['menu/getFunctions']
  const menuList = store.getters['menu/getMenuList']
  if (menuList && funcGroup) {
    if (module) {
      if (!func) {
        return menuList.includes(module)
      } else if (Array.isArray(func)) {
        const auth = func.reduce((prev: string[], cur) => {
          if (funcGroup.includes(`${module}_${cur}`)) {
            prev.push(cur)
          }
          return prev
        }, [])
        return auth.length === func.length
      } else {
        return funcGroup.includes(`${module}_${func}`)
      }
    } else {
      throw new Error('请指定权限模块!')
    }
  }
  return false
}
